package org.sharelife.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.struts2.ServletActionContext;

public class ImageCutter {

	public static boolean saveImage(ImageBean imageBean, String album) {
		String url = imageBean.getUrl();
		url = ImageCutter.formatUrl(url, album);
		File dest = new File(url);
		int top = imageBean.getTop();
		int left = imageBean.getLeft();
		int width = imageBean.getWidth();
		int height = imageBean.getHeight();
		boolean flag = false;
		String ext = UploadUtils.getExtension(dest).toLowerCase();
		BufferedImage bi = null;
		try {
			bi = (BufferedImage) ImageIO.read(dest);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		height = Math.min(height, bi.getHeight());
		width = Math.min(width, bi.getWidth());
		if (height <= 0) {
			height = bi.getHeight();
		}
		if (width <= 0) {
			width = bi.getWidth();
		}
		top = Math.min(Math.max(0, top), bi.getHeight() - height);
		left = Math.min(Math.max(0, left), bi.getWidth() - width);
		BufferedImage bi_cropper = bi.getSubimage(left, top, width, height);
		try {
			flag = ImageIO.write(bi_cropper, ext, dest);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return flag;
	}
	
	public static String formatUrl(String url, String album) {
		url = url.substring(url.lastIndexOf("/") + 1);
		url = ServletActionContext.getRequest().getSession().getServletContext().getRealPath("\\photos") + "\\" + album + "\\" + url;
		url = url.replaceAll("\\\\", "/");
		return url;
	}
}
